#include "libLUI_in.h"

void TrimRight( char *str )
{
	char	*p = NULL ;
	
	for( p = str + strlen(str) - 1 ; p >= str ; p-- )
	{
		if( (*p) == ' ' || (*p) == '\r' || (*p) == '\n' )
			(*p) = '\0' ;
		else
			break;
	}
	
	return;
}

int GetDeviceName( char *keyword , char *device_name , int device_name_bufsize )
{
	FILE		*fp = NULL ;
	char		buf[ 256 + 1 ] ;
	int		flag ;
	char		*p_begin = NULL ;
	char		*p_end = NULL ;
	char		*p_newline = NULL ;
	
	fp = fopen( "/proc/bus/input/devices" , "r" ) ;
	if( fp == NULL )
		return -1;
	
	flag = 0 ;
	while(1)
	{
		memset( buf , 0x00 , sizeof(buf) );
		if( fgets( buf , sizeof(buf) , fp ) == NULL )
			return -2;
		TrimRight( buf );
		
		if( flag == 0 )
		{
			if( strncmp( buf , "N: Name=" , 8 ) == 0 && strcasestr( buf+8 , keyword ) )
				flag = 1 ;
		}
		else if( flag == 1 )
		{
			if( strncmp( buf , "H: Handlers=" , 12 ) == 0 )
			{
				p_begin = buf + 12 ;
				while(1)
				{
					p_end = strchr( p_begin+1 , ' ' ) ;
					if( p_end == NULL )
					{
						p_newline = strchr( p_begin , '\n' ) ;
						if( p_newline )
							(*p_newline) = '\0' ;
						
						snprintf( device_name , device_name_bufsize , "%s" , p_begin );
						fclose( fp );
						return 0;
					}
					else
					{
						p_begin = p_end + 1 ;
					}
				}
			}
		}
	}
	
	fclose( fp );
	
	return -3;
}

#define ECHOFLAGS	( ECHO | ECHOE | ECHOK | ECHONL )

int SetDispMode( int fd , int option )
{
	struct termios		term ;
	
	if( tcgetattr( fd , & term ) == -1 )
		return -1;
	
	if( option )
		term.c_lflag |= ECHOFLAGS ;
	else
		term.c_lflag &= ~ ECHOFLAGS ;
	
	if( tcsetattr( fd , TCSAFLUSH , & term ) )
		return -2;
	
	return 0;
}

